<script lang="ts" setup>
import {computed, onMounted, ref} from 'vue';

const props = defineProps<{
  path: string;
  code: string;
  showCode: string;
}>();

const isCodeFold = ref(false);
const isLoading = ref(true);
const IframeRef = ref<HTMLIFrameElement | null>(null);
const iframeSrc = computed(() => `${import.meta.env.PROD ? '' : 'http://127.0.0.1:5174'}/example/#/${props.path}`);

onMounted(() => {
  IframeRef.value!.onload = () => {
    isLoading.value = false;
  };
});

const copyToClipboard = (text: string) => {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  document.body.appendChild(textArea);

  // 选择文本内容
  textArea.select();
  // 执行复制命令
  document.execCommand('copy');

  document.body.removeChild(textArea);
};

const clickCopy = () => {
  copyToClipboard(props.code);
};
</script>

<template>
  <div class="example">
    <div class="example-showcase" :iframe="`/example/#/${path}`">
      <iframe ref="IframeRef" :src="iframeSrc" frameborder="0" scrolling="no"></iframe>
    </div>
    <div class="code-btn-box">
      <el-tooltip effect="dark" content="复制代码" placement="top" append-to="body">
        <el-icon class="ml-auto cursor-pointer" @click="clickCopy"><DocumentCopy /></el-icon>
      </el-tooltip>
      <el-tooltip effect="dark" content="查看代码" placement="top" append-to="body">
        <el-icon class="ml-2 cursor-pointer" @click="isCodeFold = !isCodeFold"><Document /></el-icon>
      </el-tooltip>
    </div>
    <div v-if="isCodeFold">
      <div v-html="decodeURIComponent(showCode)" class="language-vue"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
$border-color: #dcdfe6;
.example {
  border: 1px solid $border-color;
  border-radius: 4px;
  .example-showcase {
    padding: 24px;
    border-bottom: 1px solid $border-color;
    box-sizing: content-box;
    height: 0;
  }
  .code-btn-box {
    display: flex;
    align-items: center;
    padding: 8px;
  }
  .language-vue {
    border-radius: 0 0 4px 4px;
    margin: 0;
  }
}
.cursor-pointer {
  cursor: pointer;
}
.ml-auto {
  margin-left: auto;
}
.ml-2 {
  margin-left: 8px;
}
iframe {
  height: 100%;
  width: 100%;
}
</style>
